<template>
  <search-table
    ref="searchTable"
    :columns="tableCol"
    :data="tableData"
    :total="total"
    :page.sync="queryObj.page"
    :size.sync="queryObj.rows"
    @change-size="queryAllUserSize"
    @change-page="queryAllUserPage"
  >
    <template slot="search">
      <Button
        type="primary"
        ghost
        icon="md-add"
        @click="assignUser"
        :disabled="competeStatus != '0' || notOwnCompetition"
        >添加/移除竞赛选手</Button
      >
      <Input
        v-model.trim="queryObj.userName"
        style="width: 150px; margin-left: 15px;"
        placeholder="选手名称"
        clearable
        @on-change="queryAllUserPage(1)"
      />
    </template>
    <Modal
      v-model="showModel"
      title="添加/修改竞赛选手"
      :loading="isload"
      :width="740"
      @on-ok="AddUserToSence"
      @on-visible-change="changeVisible"
      :mask-closable="false"
    >
      <Form
        ref="userFormValidate"
        :model="userFormValidate"
        :rules="userRuleValidate"
        :label-width="100"
      >
        <FormItem label="选择参赛团队" prop="groupId">
          <Select filterable
            v-model="userFormValidate.groupId"
            label-in-value
            placeholder="选择竞赛团队"
            :not-found-text="loadingData ? '加载中' : '无匹配数据'"
            filterable
            @on-change="(val) => getCurCompet(val, 'change')"
            ><!--:disabled="groupDisabled"-->
            <Option
              v-for="group in expGroupList"
              :value="group.id"
              :key="group.id"
              :label="group.name"
              :title="group.name"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem label="竞赛选手" prop="users">
          <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
            <Checkbox
              :indeterminate="indeterminate"
              :value="checkAll"
              @click.prevent.native="handleCheckAll"
              >全选</Checkbox
            >
          </div>
          <CheckboxGroup v-model="userFormValidate.users" @on-change="checkAllGroupChange">
            <Checkbox v-for="item in expGroupUsersList" :key="item.userId" :label="item.userId">{{
              item.userName
            }}</Checkbox>
          </CheckboxGroup>
        </FormItem>
      </Form>
    </Modal>
  </search-table>
</template>

<script>
import encryption from '@/libs/encryption.js'
import { queryExperGroups, getExperGroupsUsers, getuserinfo } from '@/api/users'
import { usertoSencen, usertoSencenModify, usertasklist, getUserInfo } from '@/api/drill'
import { getSenceUserList, delSenceUsers } from '@/api/knowledgeCompet'
export default {
  name: 'componentUser',
  components: {},
  inject: ['detailParent'],
  data: function() {
    let September = sessionStorage.getItem('November')
    September = JSON.parse(encryption.SelfUseDecrypt(September))
    return {
      loadingData: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      showModel: false,
      routeParams: {},
      originId: '',
      isload: true,
      tableCol: [
        {
          title: '选手名称',
          key: 'userName',
          placement: 'top-left',
          tooltip: true,
          width: 240
        },
        // {
        //   title: '竞赛团队',
        //   filters: [],
        //   key: 'teamName',
        //   tooltip: true,
        //   width: 120,
        //   filterMethod(value, row) {
        //     return row.accessGroupName.indexOf(value) > -1;
        //   }
        // },
        {
          title: '创建者',
          key: 'creator',
          tooltip: true,
          width: 120
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '登录状态',
          key: 'online',
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  color: params.row.online ? 'green' : 'red'
                }
              },
              this.onlineFilter(params.row.online)
            )
          }
        },
        {
          title: '操作',
          width: 120,
          placement: 'top-right',
          key: 'action',
          opList: [
            {
              txt: '移除',
              title: '您确定要移除该用户吗？',
              tooltip: true,
              type: 'delete',
              disabled: (data) => {
                return Boolean(this.competeStatus !== '0') || this.notOwnCompetition
              },
              on: {
                click: (data) => {
                  this.delSenceUser(data.userId)
                }
              }
            }
          ]
          // render: (h, params) => {
          //     return h('Poptip', {
          //         props:{
          //             confirm: true,
          //             title: "您确定要移除该用户吗？",
          //             width: 186
          //         },
          //         on:{
          //             'on-ok':()=>{
          //                 this.delSenceUser(params.row.userId);
          //             }
          //         }
          //     }, [
          //         h('Button', {
          //             props: {
          //                 type: 'text',
          //                 size: 'small',
          //                 disabled:Boolean(this.competeStatus!=='0') || this.notOwnCompetition
          //             },
          //             style: {
          //                 border:'none',
          //                 background:'none',
          //                 boxShadow:'none',
          //             }
          //         }, [
          //             h('img', {
          //                 attrs: {
          //                     src: Boolean(this.competeStatus!=='0') || this.notOwnCompetition ?require('../../../../assets/globalIcon/dis-remove.png'):require('../../../../assets/globalIcon/remove-hove.png'),
          //                 },
          //                 style: {
          //                     cursor: 'pointer',
          //                     'vertical-align': 'middle',
          //                     display:'inline-block',
          //                     marginBottom:'4px',
          //                 },
          //             }),
          //             h('span',{
          //                 style: {
          //                     cursor: 'pointer',
          //                     color:!(Boolean(this.competeStatus!=='0') || this.notOwnCompetition) ? '#2d8cf0' : '#c5c8ce'
          //                 },
          //             },'移除')
          //         ])
          //     ])
          // }
        }
      ],
      tableData: [],
      userFormValidate: {
        groupId: '',
        users: []
      },
      expGroupList: [],
      indeterminate: true,
      checkAll: false,
      expGroupUsersList: [],
      userRuleValidate: {
        groupId: [{ required: true, message: '请选择组', trigger: 'change' }],
        users: [{ required: true, type: 'array', message: '请选择人员', trigger: 'change' }]
      },
      senceUser: {
        creator: September.nickname,
        //"name": this.$route.query.name,
        name: '',
        prjDbId: 'knowledgePrjId',
        // "refId": this.$route.query.id,
        refId: '',
        taskType: '3',
        userType: '0',
        sceneType: '3',
        users: []
      },
      addUsers: [],
      queryObj: {
        page: 1,
        rows: 10,
        refId: ''
      },
      total: 0
    }
  },
  computed: {
    competeDetail(){
      return this.detailParent.competeDetail
    },
    createUserId(){
      return this.competeDetail.createUserId
    },
    notOwnCompetition() {
      return this.competeDetail.notOwnCompetition
    },
    competeStatus(){
      return this.competeDetail.activityStatus
    },
    setHasUser(){
      return this.detailParent.setHasUser
    }
  },
  watch: {
    
  },
  methods: {
    onlineFilter(val) {
      let str = ''
      switch (val) {
        case true:
          str = '在线'
          break
        case false:
          str = '离线'
          break
      }
      return str
    },
    changeVisible(type) {
      if (!type) {
        this.expGroupUsersList = []
        this.initFormData()
      }
    },
    initFormData() {
      this.userFormValidate = {
        groupId: '',
        users: []
      }
      this.$refs.userFormValidate.resetFields()
      this.isload = true
      this.getAllUser()
    },
    assignUser() {
      if (this.queryObj.userName) {
        this.queryObj.userName = ''
        this.queryAllUserPage(1)
      }
      this.showModel = true
      this.initFormData()
      if (this.tableData.length) {
        this.checkAll = false
        this.indeterminate = false
      }
      //this.getAllUser();
    },
    getExpGroupList() {
      this.loadingData = true
      let params = {
        visibility: 'all',
        pageIndex: 1,
        pageSize: 2147483646
      }
      queryExperGroups(params)
        .then((data) => {
          if (data.code == 1) {
            this.expGroupList = data.data.items
          } else {
            this.$Message.warning(data.message)
          }
        })
        .finally(() => {
          this.loadingData = false
        })
    },
    getCurCompet(group, type) {
      if (!group || !group.value) {
        this.checkAll = false
        this.indeterminate = false
        this.userFormValidate.users = []
        this.expGroupUsersList = []
        return
      }
      this.userFormValidate.groupId = group.value
      this.userFormValidate.groupName = group.label
      if (type === 'change') {
        this.userFormValidate.users = []
      }
      getExperGroupsUsers(group.value).then((data) => {
        if (data.code == 1) {
          this.expGroupUsersList = data.data
          //this.userFormValidate.userIdlist = data.data.map(user => user.userId);
          if (this.originId === group.value) {
            this.checkAllGroupChange(this.userFormValidate.users)
          } else {
            this.checkAll = false
            this.indeterminate = false
          }
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false
      } else {
        this.checkAll = !this.checkAll
      }
      this.indeterminate = false

      if (this.checkAll) {
        this.userFormValidate.users = this.expGroupUsersList.map((item) => item.userId)
        this.addUsers = this.userFormValidate.users.map((user) => {
          return {
            camp: 0,
            teamId: this.userFormValidate.groupId,
            teamName: this.userFormValidate.groupName,
            id: user,
            userName: (this.expGroupUsersList.find((item) => item.userId === user) || {}).userName
          }
        })
      } else {
        this.userFormValidate.users = []
      }
    },
    checkAllGroupChange(users) {
      if (users.length === this.expGroupUsersList.length) {
        this.indeterminate = false
        this.checkAll = true
      } else if (users.length > 0) {
        this.indeterminate = true
        this.checkAll = false
      } else {
        this.indeterminate = false
        this.checkAll = false
      }
      this.addUsers = users.map((user) => {
        return {
          camp: 0,
          teamId: this.userFormValidate.groupId,
          teamName: this.userFormValidate.groupName,
          id: user,
          userName: (this.expGroupUsersList.find((item) => item.userId === user) || {}).userName
        }
      })
    },
    AddUserToSence() {
      this.isload = true
      let passObj = { ...this.senceUser,refId:this.competeDetail.id,name:this.competeDetail.name, users: this.addUsers }
      let users = passObj.users
      // 测试反应可能存在添加重复用户的情况，不确定是哪里出了问题，统一在这里把可能的重复数据过滤掉
      if (users) {
        let filterUsers = []
        let userIds = []
        users.forEach((item) => {
          if (!userIds.includes(item.id)) {
            filterUsers.push(item)
            userIds.push(item.id)
          }
        })
        passObj.users = filterUsers
      }
      this.$refs.userFormValidate.validate((valid) => {
        if (valid) {
          !this.tableData.length > 0
            ? usertoSencen(passObj).then((data) => {
                this.isload = false
                if (data.code === 1) {
                  this.$Message.info('添加竞赛选手到场景成功')
                  this.showModel = false
                  this.getCompetList(1)
                } else {
                  this.$Message.error(data.message)
                  this.isload = false
                  setTimeout(() => {
                    this.isload = true
                  }, 200)
                }
              })
            : usertoSencenModify({ refId: this.competeDetail.id, dto: passObj }).then((data) => {
                this.isload = false
                if (data.code === 1) {
                  this.$Message.info('修改竞赛选手到场景成功')
                  this.getCompetList(1)
                  this.showModel = false
                } else {
                  this.$Message.error(data.message)
                  this.isload = false
                  setTimeout(() => {
                    this.isload = true
                  }, 200)
                }
              })
        } else {
          this.$Message.error('表单输入有误，请按页面提示输入!')
          this.isload = false
          setTimeout(() => {
            this.isload = true
          }, 200)
        }
      })
    },
    getCompetList(page) {
      if (page) {
        this.queryObj.page = page
      }
      this.queryObj.refId = this.competeDetail.id
      getSenceUserList(this.queryObj)
        .then((data) => {
          if (data.code == 1) {
            let users = data.attribute.dataList
            let pArr = users.map(async (user) => {
              //获取每个用户的详细信息，从而获取登录状态
              await getUserInfo(user.userId).then((data) => {
                if (data.code == 1) {
                  this.$set(user, 'online', data.data.online)
                }
              })
            })
            Promise.all(pArr).then((data) => {
              this.tableData = users
            })
            this.total = data.attribute.totalCount
            if (this.total > 0) {
              this.setHasUser(true)
            } else {
              this.setHasUser(false)
            }
          } else {
            this.setHasUser(false)
          }
        })
        .catch((error) => {
          this.setHasUser(false)
        })
    },
    queryAllUserSize(size) {
      this.queryObj.rows = size
      this.getCompetList()
    },
    queryAllUserPage(page) {
      this.queryObj.page = page
      this.getCompetList()
    },
    resetQuery() {
      this.queryObj = Object.assign(this.queryObj, {
        page: 1,
        rows: 10,
        userName: ''
      })
      this.getCompetList()
    },
    getAllUser() {
      usertasklist(this.competeDetail.id).then((data) => {
        if (data.code === 1) {
          let groupId = '',
            groupName = ''
          let datas = data.attribute.list
          let users = datas.map((item) => item.userId)
          if (users.length > 0) {
            this.originId = groupId = datas[0].refGroupId
            groupName = datas[0].teamName
          }
          this.userFormValidate = { groupId, users, groupName }
          this.getCurCompet({ value: groupId, label: groupName })
        }
      })
    },

    delSenceUser(userId) {
      delSenceUsers(this.competeDetail.id, [userId]).then((data) => {
        if (data.code === 1) {
          this.$Message.info('删除竞赛选手成功')
          this.queryObj.page
          // 删除后展示当前页，当前页没有数据展示前一页
          this.queryObj.page =
            this.tableData.length == 1 && this.queryObj.page > 1
              ? this.queryObj.page - 1
              : this.queryObj.page
          this.getCompetList()
        } else {
          this.$Message.warning(data.message)
        }
      })
    }
  },
  mounted() {
    // 获取实验组列表
    this.getExpGroupList()
    this.getCompetList(1)
  }
}
</script>

<style scoped>
.card-list /deep/ .ivu-poptip-body-message {
  color: #515a6e;
}
</style>
